package com.estudy.service;

import com.estudy.bean.StudyPlanDO;
import com.estudy.bean.StudyPlanDOExample;
import com.estudy.dao.StudyPlanDOMapper;
import com.estudy.entity.StudyPlan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author: yi.jianhua
 * @create: 2019/09/06 10:49
 */
@Service
public class PlanService {
    @Autowired
    private StudyPlanDOMapper mapper;

    public void addPlan(String planName, String startTime, String endTime, String courses, String planDesc, int uid) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        StudyPlanDO studyPlanDO = new StudyPlanDO();
        studyPlanDO.setCourses(courses);
        studyPlanDO.setCreate_time(System.currentTimeMillis());
        studyPlanDO.setStart_time(simpleDateFormat.parse(startTime).getTime());
        studyPlanDO.setEnd_time(simpleDateFormat.parse(endTime).getTime());
        studyPlanDO.setEmployee_no(uid);
        studyPlanDO.setFinsh_schedule(0);
        studyPlanDO.setPlan_desc(planDesc);
        studyPlanDO.setStatus(0);
        studyPlanDO.setPlan_name(planName);
        mapper.insertSelective(studyPlanDO);
    }

    public List<StudyPlan> queryAllPlans() {
        StudyPlanDOExample example = new StudyPlanDOExample();
        List<StudyPlanDO> studyPlanDOS = mapper.selectByExample(example);
        return convert2StudyPlanList(studyPlanDOS);
    }

    private List<StudyPlan> convert2StudyPlanList(List<StudyPlanDO> studyPlanDOS) {
        if (CollectionUtils.isEmpty(studyPlanDOS)) {
            return Collections.emptyList();
        }
        List<StudyPlan> result = new ArrayList<StudyPlan>(studyPlanDOS.size());
        for (StudyPlanDO DO : studyPlanDOS) {
            StudyPlan sp = new StudyPlan();
            sp.setCourses(DO.getCourses());
            sp.setCreateTime(DO.getCreate_time());
            sp.setEndTime(DO.getEnd_time());
            sp.setFinshSchedule(DO.getFinsh_schedule());
            sp.setId(DO.getId());
            sp.setPlanDesc(DO.getPlan_desc());
            sp.setStartTime(DO.getStart_time());
            sp.setStatus(DO.getStatus());
            sp.setUid(DO.getEmployee_no());
            sp.setPlanName(DO.getPlan_name());
            result.add(sp);
        }
        return result;
    }

    public void updatePlanStatus(String pid, int status) {
        StudyPlanDO studyPlanDO = new StudyPlanDO();
        studyPlanDO.setId(Integer.parseInt(pid));
        studyPlanDO.setStatus(status);
        mapper.updateByPrimaryKeySelective(studyPlanDO);
    }
}
